package com.hup.utils.swing.frame;

import com.hup.utils.swing.FrameUtil;
import lombok.Getter;
import lombok.Setter;

import javax.swing.*;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

/**
 * {@link BaseWindow}
 * 与 {@link JFrame}区别:
 * .dialog不出现在状态栏上,但也可以在alt+tab中看到
 * .dialog可以阻塞窗口
 *
 * @author hugan
 * @date 2020/4/10
 */
public class BaseDialog extends JDialog implements BaseWindow {

    @Setter
    @Getter
    private String baseTitle;
    /**
     * 默认为单例窗口
     */
    @Getter
    private boolean singleton = true;

    /**
     * <pre>
     * 构造省缺对象
     *  .setModal(true), {@link #setModal(boolean)}
     *  .默认是单例窗口,
     *
     * </pre>
     *
     * @param title 窗口标题
     */
    public BaseDialog(String title) {
        super();
        setTitle(title);
        setBaseTitle(title);
        onCreate();
    }

    @Override
    public void onCreate() {
        initIcon();
        setModal(true);

        setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                boolean dispose = BaseDialog.this.onWindowClosing(e);
                if (dispose) dispose();
            }
        });
        FrameUtil.addVisibleListener(this, this);

        if (isSingleton()) SingletonWindowHelper.addWindow(this);
    }

    @Override
    public void onShown() {

    }

    /**
     * 用户主动关闭窗口[关闭按钮,快捷键关闭]操作:默认是 {@link #onCancel()}
     *
     * @return 总是返回false,
     */
    @Override
    public boolean onWindowClosing(WindowEvent e) {
        onCancel();
        return false;
    }

    /**
     * 应该不用重写本方法的, 前有 {@link #onWindowClosing(WindowEvent)},后有 {@link #onHidden(boolean)}
     */
    @Override
    public final void dispose() {
        super.dispose();
        if (isSingleton()) SingletonWindowHelper.removeWindow(this);
    }

    /**
     * 窗口关闭后的回调
     *
     * @param dispose true-点关闭按钮,dispose();false-setVisible(false)
     */
    @Override
    public void onHidden(boolean dispose) {
    }

    /**
     * 默认的[取消方法][关闭按钮,快捷键关闭窗口方法],默认时为 {@link #dispose()}
     */
    public void onCancel() {
        dispose();
    }

    @Override
    public void setSingleton(boolean singleton) {
        this.singleton = singleton;
        if (!isSingleton()) SingletonWindowHelper.removeWindow(this);
    }

    /**
     * 设置按下[Esc]后调用 {@link #onCancel()}
     */
    public void setEscapeCancelable(boolean cancelable) {
        if (cancelable) {
            ((JComponent) getContentPane()).registerKeyboardAction(e -> onCancel(),
                    KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_IN_FOCUSED_WINDOW);
        } else {
            ((JComponent) getContentPane()).unregisterKeyboardAction(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0));
        }
    }

}
